<?php

declare(strict_types=1);

namespace App\Master\Framework\Library\Wechat;


use App\Master\Framework\Extend\Module;
use App\Master\Framework\Library\Library;
use Illuminate\Support\Facades\Cache;

/**
 * 扩展返回工具
 */
class MiniAppLibrary extends Library
{
    protected string $base_uri = 'https://api.weixin.qq.com';
    protected array $config = [];

    /**
     * 实例化
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function __construct()
    {
        // 微信开发配置
        $config = Module::_SetupModule("WechatConfig")['mini'] ?? [];
        $this->config = [
            'app_id'  => $config['app_id'] ?? '',
            'secret'  => $config['app_secret'] ?? '',
            'token'   => $config['token'] ?? '',
            'aes_key' => $config['aes_key'] ?? '',
        ];
    }

    /**
     * 授权
     * @param $code
     * @return bool
     */
    public function jscode2session($code)
    {
        $data = [
            'appid'      => $this->config['app_id'],
            'secret'     => $this->config['secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code',
        ];
        $response = $this->getJson("/sns/jscode2session", $data);
        if ($response->getStatusCode() != 200) {
            return $this->error($response->getReasonPhrase());
        }

        $json = $response->getBody()->getContents();
        $body = json_decode($json, true);
        if (!isset($body['errcode']) || $body['errcode'] != 0) {
            return $this->error(!empty($body['errmsg']) ? $body['errmsg'] : 'Error_0', $body);
        }

        return $this->success('获取成功', $body);
    }
}